package com.hice.demo.dubbo.api.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.hice.demo.dubbo.api.service.ServiceTest;
import com.hice.demo.dubbo.message.model.Message;
import com.hice.demo.dubbo.message.service.MessageService;
import com.hice.demo.dubbo.user.model.User;
import com.hice.demo.dubbo.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by hyson on 2017/3/13.
 */
@Slf4j
@RestController
public class UserController {
    @Reference(version = "1.0.0")
    UserService userService;
    @Reference(version = "1.0.0")
    MessageService messageService;
    @Autowired
    ServiceTest serviceTest;

    @GetMapping("/add")
    public String add(User user){
        String result = "fail";
        Message message = new Message();
        try {
            if (userService.add(user)) {
                message.setName(user.getName());
                message.setContent("成功");
            } else {
                message.setName(user.getName());
                message.setContent("失败");
            }
            if(messageService.add(message)){
                result = "success";
            }
        }catch (Exception e){
            log.info("异常{}", e.getMessage());
        }
        return result;
    }

    /**
     * 测试dubbo分布式事务回滚
     * @param id
     * @return
     */
    @GetMapping("/rollback")
    public String rollback(Long id){
        String result = "fail";
        try {
            userService.del(id);
            System.out.println(1/0);
            messageService.del(id);
        }catch (Exception e){
            log.info("异常{}", e.getMessage());
        }
        return result;
    }

    @GetMapping("/rollback2")
    public String rollback2(Long id){
        String result = "fail";
        try {
            if (serviceTest.dubboDel(id)) {
                log.info("dubbo删除成功");
            }
        }catch (Exception e){
            log.info("异常{}", e.getMessage());
        }
        return result;
    }
}  